package com.bear.newsset.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bear.newsset.R;
import com.bear.newsset.dao.entity.NewsLikeSqlEntity;
import com.bear.newsset.dao.sql.NewsStatusSQL;
import com.bear.newsset.entity.NewsDataEntity;
import com.bear.newsset.util.AnimUtil;
import com.bear.newsset.util.Utils;
import com.bear.newsset.widget.BaseActivity;
import com.bear.newsset.widget.ContentWebView;

import java.lang.ref.WeakReference;

/**
 * 新闻内容页面
 */
public class ContentActivity extends BaseActivity {
    public static final String NAME_NEWS_SUB_ITEM_ENTITY = "newsSubItemEntity";
    private Context mContext;
    private ContentWebView webView;
    private TextView tvTitle;
    private ImageView ivBackBtn, ivLoading;

    private NewsDataEntity mData = null;
    private ThisHandler mThisHandler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content);
        mContext = this;
        initIntent();
        initView();
        initData();
        initListener();
    }

    private void initIntent() {
        Bundle b = getIntent().getExtras();
        Object obj = null;
        if( b != null ) obj = b.getSerializable( NAME_NEWS_SUB_ITEM_ENTITY );
        if( obj instanceof NewsDataEntity ) mData = (NewsDataEntity) obj;
    }

    /**
     * 初始化视图
     */
    private void initView() {
        webView = findViewById(R.id.content_webview_web);
        ivLoading = findViewById(R.id.content_iv_loading);
        tvTitle = findViewById(R.id.tb_content_tv_title);
        ivBackBtn = findViewById(R.id.tb_content_iv_back_btn);
        //隐藏标题
        tvTitle.setVisibility(View.INVISIBLE);
        //显示toolbar返回按钮
        ivBackBtn.setVisibility(View.VISIBLE);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mThisHandler = new ThisHandler(this);
        //禁用默认方式打开点击的链接
//        webView.setEnableDefaultTouchLoad( false );

        if( mData != null ) {
            String title = mData.getAppCode();
            if( title == null || title.equals("") ) title = "无名鸡新闻";
            //设置标题
            tvTitle.setText(title);
            //保存到历史
            if( mData.getId() != null ) saveToHistory( mData.getId() );
            //设置新闻内容
            webView.loadUrl( mData.getUrl() );
        }else {
            Toast.makeText(this,"(TAT) 本鸡把新闻弄丢了！",Toast.LENGTH_SHORT).show();
            finish();//关闭该页面
        }
    }

    /**
     * 保存到历史
     * @param newsId    新闻列表
     */
    private void saveToHistory(String newsId) {
        NewsLikeSqlEntity e = NewsStatusSQL.getInstance().queryNewsLikeSqlForNewsId( newsId );
        if( !e.getIsHistory() ) {
            String account = ((NSApplication) (getApplication()))
                    .getAccountEntity()
                    .getAccount();

            e.setAccount( account );
            e.setNewsId( newsId );
            e.setIsHistory( true );
            NewsStatusSQL.getInstance().insertNewsLikeSql( e );
        }
    }

    private void initListener() {
        //关闭页面
        ivBackBtn.setOnClickListener(view -> ((Activity)mContext).finish());

        //滑动一段后隐藏/显示标题
        webView.getViewTreeObserver().addOnScrollChangedListener(() -> {
            int scrollY = webView.getView().getScrollY();
            int isShowTitle;
            isShowTitle = scrollY >= Utils.dp2Px(mContext, 100) ? 1 : 0;
            mThisHandler.sendEmptyMessage( isShowTitle );
        });

//        //监听链接加载来重新打开点击的链接
//        webView.setShouldOverrideUrlLoadingListener((v, url) -> Utils.startContentActivity(
//                v.getContext(), new NewsDataEntity()
//                        .setAppCode("内部页面")
//                        .setUrl( url )
//        ));

        //webView touch监听
        Utils.setOnSuperTouchListener(webView, (v, event) -> {
            //实现侧滑返回
            onSwipeBackTouchEvent( event );
            return false;
        });

        //加载页面 touch监听
        Utils.setOnSuperTouchListener(ivLoading, (v, event) -> {
            //实现侧滑返回
            onSwipeBackTouchEvent( event );
            return false;
        });
    }

    /**
     * Handler
     */
    private static class ThisHandler extends Handler {
        ContentActivity mActivity;
        ThisHandler(ContentActivity mActivity) {
            this.mActivity = new WeakReference<>(mActivity).get();
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch ( msg.what ) {
                case 0://隐藏标题
                    if( mActivity.tvTitle.getVisibility() == View.INVISIBLE ) break;
                    mActivity.tvTitle.setVisibility( View.INVISIBLE );
                    break;
                case 1://显示标题
                    if( mActivity.tvTitle.getVisibility() == View.VISIBLE ) break;
                    AnimUtil.loadAnimForToTop( mActivity, mActivity.tvTitle,
                            AnimUtil.SHOW_STATUS.VISIBLE );
                    break;
            }
        }
    }
}
